#! python3
# coding=utf-8
from lib.bmobHelper import BmobHelper
import urllib.request
import urllib.parse
import json
import time
import config

def getLocalbicoinsOrderBook():
    result = {'bid': 0, 'ask': 0}
    try:
        reqAskOrders = urllib.request.urlopen('https://localbitcoins.com/buy-bitcoins-online/cny/.json', timeout=20)
        reqBidOrders = urllib.request.urlopen('https://localbitcoins.com/sell-bitcoins-online/cny/.json', timeout=20)

        if reqAskOrders.status != 200 or reqBidOrders.status != 200:
            return result
        else:
            askOrdersBytes = reqAskOrders.read()
            bidOrdersBytes = reqBidOrders.read()
            askOrdersStr = askOrdersBytes.decode('utf-8')
            bidOrdersStr = bidOrdersBytes.decode('utf-8')
            reqAskOrders.close()
            reqBidOrders.close()
            
            jsonAskOrders = json.loads(askOrdersStr)
            jsonBidOrders = json.loads(bidOrdersStr)

            askPriceList = []
            bidPriceList = []
            for item in jsonAskOrders['data']['ad_list']:
                askPriceList.append(float(item['data']['temp_price']))
            for item in jsonBidOrders['data']['ad_list']:
                bidPriceList.append(float(item['data']['temp_price']))
            
            askPriceList.sort()
            bidPriceList.sort(reverse=True)
            result['bid'] = bidPriceList[0]
            result['ask'] = askPriceList[0]
    except Exception as ex:
        print('Get LocalBitcoins orderbook Failed!' + str(ex))
    return result

def getOKOrderBook():
    result = {'bid': 0, 'ask': 0}
    try:
        reqTicker = urllib.request.urlopen('https://www.okcoin.cn/api/v1/ticker.do?symbol=btc_cny', timeout=20)

        if reqTicker.status != 200:
            return result
        else:
            tickerBytes = reqTicker.read()
            tickerStr = tickerBytes.decode('utf-8')
            reqTicker.close()
            
            jsonTicker = json.loads(tickerStr)

            result['bid'] = float(jsonTicker['ticker']['buy'])
            result['ask'] = float(jsonTicker['ticker']['sell'])
    except Exception as ex:
        print('Get OKcoin orderbook Failed!' + str(ex))
    return result

def getBitmexOrderBook():
    result = {'bid': 0, 'ask': 0}
    exchange_rate = 6.86
    try:
        reqOrderBook = urllib.request.urlopen('https://www.bitmex.com/api/bitcoincharts/XBTM17/orderBook', timeout=20)

        if reqOrderBook.status != 200:
            return result
        else:
            orderBookBytes = reqOrderBook.read()
            orderBookStr = orderBookBytes.decode('utf-8')
            reqOrderBook.close()

            jsonOrderBook = json.loads(orderBookStr)

            result['bid'] = jsonOrderBook['bids'][0][0] * exchange_rate
            result['ask'] = jsonOrderBook['asks'][0][0] * exchange_rate
    except Exception as ex:
        print('Get Bitmex orderbook Failed!' + str(ex))
    return result

def analysisDiff(localbitcoinsOrderBook, bitmexOrderBook):
    result = {'diffOpenInPercent': 0, 'diffCloseInPercent': 0}
    if localbitcoinsOrderBook['bid'] != 0 and localbitcoinsOrderBook['ask'] != 0 \
        and bitmexOrderBook['bid'] != 0 and bitmexOrderBook['ask'] != 0:
        # 开仓差价，即场外买，期货卖，diff=期货价-场外价
        diffOpen = bitmexOrderBook['bid'] - localbitcoinsOrderBook['ask']
        diffOpenInPercent = diffOpen / bitmexOrderBook['bid']
        diffOpenInPercent = int(diffOpenInPercent*10000)/100

        # 平仓差价，即期货平仓，场外卖，diff=场外价-期货价
        diffClose = localbitcoinsOrderBook['bid'] - bitmexOrderBook['ask']
        diffCloseInPercent = diffClose / bitmexOrderBook['ask']
        diffCloseInPercent = int(diffCloseInPercent*10000)/100

        result['diffOpenInPercent'] = diffOpenInPercent
        result['diffCloseInPercent'] = diffCloseInPercent
    return result

def post_to_slack(msg):
    channels = ['#场外场内价格比较', '@shenchong']
    token = 'xoxp-180800956182-180800956246-180095641365-0ad9fa4b6960f79ab83ae01ed93e1f58'
    datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))

    print(datetime + msg)
    for channel in channels:
        post_data = {'text': msg, 'channel': channel, 'token': token}
        enc_post_data = urllib.parse.urlencode(post_data).encode(encoding='UTF8')
        url = 'https://{}/api/{}'.format('slack.com', 'chat.postMessage')
        try:
            urllib.request.urlopen(url, enc_post_data, timeout=10)
        except Exception as ex:
            print('Post fail. Fail to connect Slack!')

def recordInBmob(result):
    if result['diffOpenInPercent'] != 0 and result['diffCloseInPercent'] != 0:
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
        record = BmobHelper()
        record.record_op(datetime, result['diffOpenInPercent'], result['diffCloseInPercent'])
    
def onTick():
    # localbitcoinsOrderBook = getLocalbicoinsOrderBook()
    OkcoinOrderBook = getOKOrderBook()
    bitmexOrderBook = getBitmexOrderBook()
    priceDiff = analysisDiff(OkcoinOrderBook, bitmexOrderBook)

    if priceDiff['diffOpenInPercent'] > 3 or priceDiff['diffCloseInPercent'] > 3:
        post_to_slack(str(priceDiff))

    recordInBmob(priceDiff)


def main():
    while True:
        onTick()
        time.sleep(config.TickInterval)


if __name__ == '__main__':
    main()
